import sys
import subprocess
import os.path
from datetime import datetime
from djvu_ocr import settings

def launchDocumentToDjvu(input, output):
    launchSubProcess("document.express.path", "documenttodjvu.exe.with.params", input, output)
    #launchSubProcess("document.express.path", "phototodjvu.exe.with.params", input, output) #TODO

def launchPdfToDjvu(input, output):
    launchSubProcess("document.express.path", "pdftodjvu.exe.with.params", input, output)

def launchDjvuToXML(input, output):
    launchSubProcess("document.express.path", "djvutoxml.exe.with.params", input, output)

def launchDjvuParseXML(input):
    launchSubProcess("document.express.path", "djvuparsexml.exe.with.params", input)
    
def launchSubProcess(cmdPathKey, cmdKey, input = None, output = None):
    cmd = settings.getProperty(cmdPathKey) + settings.getProperty(cmdKey)
    if input != None:
        cmd += " " + input
        if output != None:
            cmd += " " + output
    
    print cmd
    
    proc = subprocess.Popen(cmd)
    proc.wait()
    
def launchXsltProcessing(input, output, replace, replaceWith):
    processed = file(output, "w");
    asString = open(input).read()
    replace = replace.replace("\\", "/").replace("\"", "")
    processed.write(asString.replace(replace, replaceWith))

def process(tiffDir, pdf):
    inFolder = settings.getProperty("document.express.input.folder")
    outFolder = settings.getProperty("document.express.output.folder")
    
    pdfFullFilename = os.path.basename(pdf)
    pdfOnlyFilename, pdfOnlyExtension = os.path.splitext(pdfFullFilename)
    
    djvuPathPrefix = outFolder + "\\" + pdfOnlyFilename + "_" #+ str(datetime.now())
    djvuFromTiffs = djvuPathPrefix + ".djvu"
    djvuFromPdf = "\"" + djvuPathPrefix + "_2" + ".djvu\""
    metadataPre = djvuPathPrefix + "_pre.xml"
    metadataPost = djvuPathPrefix + "_post.xml"
    
    launchDocumentToDjvu(input = "--filelist=desc.txt", output = "\"" + djvuFromTiffs + "\"") # ko-szmar
    
    launchPdfToDjvu(input = "\"" + pdf + ".pdf\"", output = djvuFromPdf)
    
    launchDjvuToXML(input = djvuFromPdf, output = metadataPre)
    
    launchXsltProcessing(input = metadataPre, output = metadataPost, replace = djvuFromPdf, replaceWith = djvuFromTiffs)
   
    launchDjvuParseXML(metadataPost)
    